package org.jks.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.constant.SysError;
import org.jks.model.Privilege;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UITable;
import org.jks.service.PrivilegeService;
import org.jks.util.PrivilegeUtil;
import org.jks.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/privilege")
public class PrivilegeController {
	@Autowired
	PrivilegeService privilegeService;

	@RequestMapping("/add")
	public void add(Privilege privilege, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			privilegeService.save(privilege);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	@RequestMapping("/delete")
	public void delete(long id, HttpServletRequest request, HttpServletResponse response){
		try{
			privilegeService.delete(id);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/update")
	public void update(Privilege privilege, HttpServletRequest request, HttpServletResponse response){
		try{
			privilegeService.update(privilege);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/all")
	public void all(HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			List<Privilege> privileges = privilegeService.all();
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setRows(privileges);
			ar.setData(table);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/list")
	public void list(HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			List<Privilege> privileges = privilegeService.all();
			List<Privilege> privs = new ArrayList<Privilege>();
			for(Privilege privilege: privileges){
				if(privilege.getId() > 26){
					privs.add(privilege);
				}
			}
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setRows(privs);
			ar.setData(table);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/has_privilege")
	public void hasPrivilege(@RequestParam String action, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ActionResult ar = new ActionResult();
		if(PrivilegeUtil.hasPrivlege(session, action) == SysError.SUCCESS){
			ar.setData(true);
		}
		else{
			ar.setData(false);
		}
		
		ar.setSuccess(true);
		ResponseUtil.returnJson(response, ar);
	}
}
